Various extensions to JSONValue#68
Conversation
Codecov Report
@@ Coverage Diff @@
## main #68 +/- ##
==========================================
+ Coverage 85.91% 86.19% +0.28%
==========================================
Files 13 13
Lines 1271 1355 +84
==========================================
+ Hits 1092 1168 +76
- Misses 179 187 +8
Continue to review full report at Codecov.
|
t089
left a comment
There was a problem hiding this comment.
I would like these convenience accessors, but I would be very careful with the implementation of Codable for JSONValue. Especially the JSON number will only be lossy encoded and decoded.
| case .number(let n): | ||
| if let int = self.intValue { | ||
| try container.encode(int) | ||
| } else if let double = self.doubleValue { |
There was a problem hiding this comment.
Unfortunately, I think this might introduce rounding errors. Because JSON represents numbers as String, you might loose precision when converting to Double and then back to String. Unfortunately, I don't think there is an elegant way to avoid floating point arithmetic when going through the Codable interface.
| let container = try decoder.singleValueContainer() | ||
| if let int = try? container.decode(Int.self) { | ||
| self = .number(String(int)) | ||
| } else if let double = try? container.decode(Double.self) { |
There was a problem hiding this comment.
Same for the decoding: going through a floating point number can introduce artifacts from floating point arithmetic.
This PR adds the following extensions to the
JSONValueenum:ExpressibleByXLiteralprotocols (so e.g.let x: JSON = ["y": [ "z": [1, 2.2, false]]]is possible)Codableprotocol (if you want a loosely typed value as part of yourCodablestruct, for example)